package me.zhengjie.config;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.service.FlywayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * Flyway 初始化监听器
 * 
 * @author zhengjie
 * @date 2024-01-01
 */
@Slf4j
@Component
public class FlywayInitializer {

    @Autowired
    private FlywayService flywayService;

    /**
     * 应用启动完成后执行 Flyway 迁移
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        try {
            log.info("应用启动完成，开始执行 Flyway 数据库迁移...");
            
            // 验证迁移脚本
            flywayService.validate();
            
            // 执行迁移
            flywayService.migrate();
            
            // 输出迁移信息
            String migrationInfo = flywayService.getMigrationInfo();
            log.info("Flyway 迁移完成，迁移信息：\n{}", migrationInfo);
            
        } catch (Exception e) {
            log.error("Flyway 迁移失败", e);
            // 注意：这里不抛出异常，避免阻止应用启动
            // 在生产环境中，你可能希望在这里抛出异常
        }
    }
} 